{% extends "base.html" %}

{% block title %}目标管理 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1><i class="bi bi-trophy"></i> 目标管理</h1>
            <p class="text-muted">规划目标，追踪进度，实现梦想</p>
        </div>
        <div>
            <button class="btn btn-danger btn-custom me-2" onclick="clearCompletedGoals()">
                <i class="bi bi-trash"></i> 清除已完成
            </button>
            <button class="btn btn-primary btn-custom" data-bs-toggle="modal" data-bs-target="#addGoalModal">
                <i class="bi bi-plus-circle"></i> 添加目标
            </button>
        </div>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-primary" id="stat-active">0</h3>
                <p class="text-muted mb-0">进行中</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-success" id="stat-completed">0</h3>
                <p class="text-muted mb-0">已完成</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-warning" id="stat-total">0</h3>
                <p class="text-muted mb-0">总目标数</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-info" id="stat-completion-rate">0%</h3>
                <p class="text-muted mb-0">完成率</p>
            </div>
        </div>
    </div>
</div>

<!-- 过滤器 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <select class="form-select" id="filter-status" onchange="loadGoals()">
                    <option value="">所有状态</option>
                    <option value="进行中">进行中</option>
                    <option value="已完成">已完成</option>
                    <option value="已放弃">已放弃</option>
                </select>
            </div>
            <div class="col-md-6">
                <select class="form-select" id="filter-category" onchange="loadGoals()">
                    <option value="">所有分类</option>
                    <option value="事业">事业</option>
                    <option value="学习">学习</option>
                    <option value="健康">健康</option>
                    <option value="财务">财务</option>
                    <option value="其他">其他</option>
                </select>
            </div>
        </div>
    </div>
</div>

<!-- 目标列表 -->
<div id="goals-list">
    <p class="text-center text-muted">加载中...</p>
</div>

<!-- 添加目标模态框 -->
<div class="modal fade" id="addGoalModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加目标</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="add-goal-form">
                    <div class="mb-3">
                        <label class="form-label">目标标题 *</label>
                        <input type="text" class="form-control" id="goal-title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">目标描述</label>
                        <textarea class="form-control" id="goal-description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="goal-category">
                            <option value="事业">事业</option>
                            <option value="学习">学习</option>
                            <option value="健康">健康</option>
                            <option value="财务">财务</option>
                            <option value="其他" selected>其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">目标完成日期</label>
                        <input type="date" class="form-control" id="goal-target-date">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addGoal()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 目标详情模态框 -->
<div class="modal fade" id="goalDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detail-goal-title"></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="detail-goal-id">
                
                <!-- 进度条 -->
                <div class="mb-4">
                    <div class="d-flex justify-content-between mb-2">
                        <span>完成进度</span>
                        <span id="detail-progress-text">0%</span>
                    </div>
                    <div class="progress progress-custom">
                        <div class="progress-bar bg-success" id="detail-progress-bar" style="width: 0%"></div>
                    </div>
                </div>
                
                <!-- 子任务 -->
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6><i class="bi bi-list-task"></i> 子任务</h6>
                        <button class="btn btn-sm btn-outline-primary" onclick="showAddTaskForm()">
                            <i class="bi bi-plus"></i> 添加
                        </button>
                    </div>
                    <div id="add-task-form" style="display:none;" class="mb-3">
                        <div class="input-group">
                            <input type="text" class="form-control" id="new-task-title" placeholder="输入任务名称">
                            <button class="btn btn-primary" onclick="addTask()">添加</button>
                            <button class="btn btn-secondary" onclick="hideAddTaskForm()">取消</button>
                        </div>
                    </div>
                    <div id="tasks-list"></div>
                </div>
                
                <!-- 里程碑 -->
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6><i class="bi bi-flag"></i> 里程碑</h6>
                        <button class="btn btn-sm btn-outline-primary" onclick="showAddMilestoneForm()">
                            <i class="bi bi-plus"></i> 添加
                        </button>
                    </div>
                    <div id="add-milestone-form" style="display:none;" class="mb-3">
                        <div class="input-group">
                            <input type="text" class="form-control" id="new-milestone-title" placeholder="里程碑标题">
                            <input type="date" class="form-control" id="new-milestone-date">
                            <button class="btn btn-primary" onclick="addMilestone()">添加</button>
                            <button class="btn btn-secondary" onclick="hideAddMilestoneForm()">取消</button>
                        </div>
                    </div>
                    <div id="milestones-list"></div>
                </div>
                
                <!-- 反思笔记 -->
                <div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6><i class="bi bi-journal-text"></i> 反思笔记</h6>
                        <button class="btn btn-sm btn-outline-primary" onclick="showAddReflectionForm()">
                            <i class="bi bi-plus"></i> 添加
                        </button>
                    </div>
                    <div id="add-reflection-form" style="display:none;" class="mb-3">
                        <textarea class="form-control mb-2" id="new-reflection-content" rows="3" placeholder="写下您的想法..."></textarea>
                        <button class="btn btn-primary btn-sm" onclick="addReflection()">保存</button>
                        <button class="btn btn-secondary btn-sm" onclick="hideAddReflectionForm()">取消</button>
                    </div>
                    <div id="reflections-list"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentGoals = [];
let currentGoalDetail = null;
let goalDetailModalInstance = null;  // 模态框单例

// 加载统计
function loadStats() {
    fetch('/goal/api/stats')
        .then(response => response.json())
        .then(data => {
            document.getElementById('stat-active').textContent = data.active_count;
            document.getElementById('stat-completed').textContent = data.completed;
            document.getElementById('stat-total').textContent = data.total;
            
            const completionRate = data.total > 0 
                ? Math.round((data.completed / data.total) * 100) 
                : 0;
            document.getElementById('stat-completion-rate').textContent = completionRate + '%';
        });
}

// 加载目标列表
function loadGoals() {
    const status = document.getElementById('filter-status').value;
    const category = document.getElementById('filter-category').value;
    
    let url = '/goal/api/goals?';
    if (status) url += `status=${status}&`;
    if (category) url += `category=${category}`;
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            currentGoals = data.goals;
            renderGoals();
        });
}

// 渲染目标列表
function renderGoals() {
    const container = document.getElementById('goals-list');
    
    if (currentGoals.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">暂无目标</p>';
        return;
    }
    
    container.innerHTML = currentGoals.map(goal => {
        const statusClass = goal.status === '已完成' ? 'success' : 
                          goal.status === '已放弃' ? 'secondary' : 'primary';
        const targetDate = goal.target_date ? new Date(goal.target_date).toLocaleDateString('zh-CN') : '无期限';
        
        return `
            <div class="card custom-card mb-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-3">
                        <div class="flex-grow-1">
                            <h5 class="mb-1">
                                ${goal.title}
                                <span class="badge bg-${statusClass} ms-2">${goal.status}</span>
                                <span class="badge bg-secondary ms-1">${goal.category}</span>
                            </h5>
                            <p class="text-muted mb-2">${goal.description || '无描述'}</p>
                            <small class="text-muted">
                                <i class="bi bi-calendar"></i> 目标日期: ${targetDate}
                            </small>
                        </div>
                        <div>
                            <button class="btn btn-sm btn-outline-primary" onclick="viewGoalDetail(${goal.id})">
                                <i class="bi bi-eye"></i> 查看
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteGoal(${goal.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div>
                        <div class="d-flex justify-content-between mb-1">
                            <span>进度</span>
                            <span>${goal.progress}%</span>
                        </div>
                        <div class="progress progress-custom">
                            <div class="progress-bar bg-success" style="width: ${goal.progress}%"></div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 添加目标
function addGoal() {
    const data = {
        title: document.getElementById('goal-title').value,
        description: document.getElementById('goal-description').value,
        category: document.getElementById('goal-category').value,
        target_date: document.getElementById('goal-target-date').value
    };
    
    if (!data.title) {
        showAlert('请输入目标标题', 'warning');
        return;
    }
    
    fetch('/goal/api/goals', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('添加成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addGoalModal')).hide();
            document.getElementById('add-goal-form').reset();
            loadGoals();
            loadStats();
        }
    });
}

// 查看目标详情
function viewGoalDetail(goalId) {
    fetch(`/goal/api/goals/${goalId}`)
        .then(response => response.json())
        .then(data => {
            currentGoalDetail = data;
            document.getElementById('detail-goal-id').value = data.id;
            document.getElementById('detail-goal-title').textContent = data.title;
            document.getElementById('detail-progress-text').textContent = data.progress + '%';
            document.getElementById('detail-progress-bar').style.width = data.progress + '%';
            
            renderTasks(data.tasks);
            renderMilestones(data.milestones);
            renderReflections(data.reflections);
            
            // 使用单例模式管理模态框，避免背景叠加
            if (!goalDetailModalInstance) {
                goalDetailModalInstance = new bootstrap.Modal(document.getElementById('goalDetailModal'));
            }
            goalDetailModalInstance.show();
        });
}

// 渲染子任务
function renderTasks(tasks) {
    const container = document.getElementById('tasks-list');
    
    if (tasks.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无子任务</p>';
        return;
    }
    
    container.innerHTML = tasks.map(task => `
        <div class="d-flex align-items-center justify-content-between mb-2 border-bottom pb-2">
            <div class="form-check flex-grow-1">
                <input class="form-check-input" type="checkbox" ${task.completed ? 'checked' : ''} 
                       onchange="toggleTask(${task.id}, this.checked)">
                <label class="form-check-label ${task.completed ? 'text-decoration-line-through' : ''}">
                    ${task.title}
                </label>
            </div>
            <div class="btn-group btn-group-sm">
                <button class="btn btn-outline-primary btn-sm" onclick="editTask(${task.id}, '${task.title.replace(/'/g, "\\'")}')">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-outline-danger btn-sm" onclick="deleteTask(${task.id})">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        </div>
    `).join('');
}

// 渲染里程碑
function renderMilestones(milestones) {
    const container = document.getElementById('milestones-list');
    
    if (milestones.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无里程碑</p>';
        return;
    }
    
    container.innerHTML = milestones.map(m => {
        const targetDate = m.target_date ? new Date(m.target_date).toLocaleDateString('zh-CN') : '';
        return `
            <div class="d-flex align-items-center justify-content-between mb-2 border-bottom pb-2">
                <div class="form-check flex-grow-1">
                    <input class="form-check-input" type="checkbox" ${m.completed ? 'checked' : ''} 
                           onchange="toggleMilestone(${m.id}, this.checked)">
                    <label class="form-check-label ${m.completed ? 'text-decoration-line-through' : ''}">
                        ${m.title} ${targetDate ? `(${targetDate})` : ''}
                    </label>
                </div>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary btn-sm" onclick="editMilestone(${m.id}, '${m.title.replace(/'/g, "\\'")}', '${m.target_date || ''}')">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-outline-danger btn-sm" onclick="deleteMilestone(${m.id})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }).join('');
}

// 渲染反思笔记
function renderReflections(reflections) {
    const container = document.getElementById('reflections-list');
    
    if (reflections.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无反思笔记</p>';
        return;
    }
    
    container.innerHTML = reflections.map(r => {
        const date = new Date(r.created_at).toLocaleDateString('zh-CN');
        return `
            <div class="card mb-2">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <p class="mb-1">${r.content}</p>
                            <small class="text-muted">${date}</small>
                        </div>
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary btn-sm" onclick="editReflection(${r.id}, '${r.content.replace(/'/g, "\\'")}')">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn btn-outline-danger btn-sm" onclick="deleteReflection(${r.id})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 添加子任务
function showAddTaskForm() {
    document.getElementById('add-task-form').style.display = 'block';
}

function hideAddTaskForm() {
    document.getElementById('add-task-form').style.display = 'none';
    document.getElementById('new-task-title').value = '';
}

function addTask() {
    const goalId = document.getElementById('detail-goal-id').value;
    const title = document.getElementById('new-task-title').value;
    
    if (!title) return;
    
    fetch(`/goal/api/goals/${goalId}/tasks`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ title: title })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            hideAddTaskForm();
            viewGoalDetail(goalId);
            loadGoals();
        }
    });
}

function toggleTask(taskId, completed) {
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/tasks/${taskId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ completed: completed })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            viewGoalDetail(goalId);
            loadGoals();
        }
    });
}

// 编辑子任务
function editTask(taskId, currentTitle) {
    const newTitle = prompt('修改任务名称:', currentTitle);
    if (!newTitle || newTitle === currentTitle) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/tasks/${taskId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ title: newTitle })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('修改成功', 'success');
            viewGoalDetail(goalId);
            loadGoals();
        }
    });
}

// 删除子任务
function deleteTask(taskId) {
    if (!confirm('确定要删除这个子任务吗？')) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/tasks/${taskId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            viewGoalDetail(goalId);
            loadGoals();
        }
    });
}

// 添加里程碑
function showAddMilestoneForm() {
    document.getElementById('add-milestone-form').style.display = 'block';
}

function hideAddMilestoneForm() {
    document.getElementById('add-milestone-form').style.display = 'none';
    document.getElementById('new-milestone-title').value = '';
    document.getElementById('new-milestone-date').value = '';
}

function addMilestone() {
    const goalId = document.getElementById('detail-goal-id').value;
    const data = {
        title: document.getElementById('new-milestone-title').value,
        target_date: document.getElementById('new-milestone-date').value
    };
    
    if (!data.title) return;
    
    fetch(`/goal/api/goals/${goalId}/milestones`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            hideAddMilestoneForm();
            viewGoalDetail(goalId);
        }
    });
}

function toggleMilestone(milestoneId, completed) {
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/milestones/${milestoneId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ completed: completed })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            viewGoalDetail(goalId);
        }
    });
}

// 编辑里程碑
function editMilestone(milestoneId, currentTitle, currentDate) {
    const newTitle = prompt('修改里程碑名称:', currentTitle);
    if (!newTitle || newTitle === currentTitle) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/milestones/${milestoneId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ title: newTitle })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('修改成功', 'success');
            viewGoalDetail(goalId);
        }
    });
}

// 删除里程碑
function deleteMilestone(milestoneId) {
    if (!confirm('确定要删除这个里程碑吗？')) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/milestones/${milestoneId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            viewGoalDetail(goalId);
        }
    });
}

// 添加反思笔记
function showAddReflectionForm() {
    document.getElementById('add-reflection-form').style.display = 'block';
}

function hideAddReflectionForm() {
    document.getElementById('add-reflection-form').style.display = 'none';
    document.getElementById('new-reflection-content').value = '';
}

function addReflection() {
    const goalId = document.getElementById('detail-goal-id').value;
    const content = document.getElementById('new-reflection-content').value;
    
    if (!content) return;
    
    fetch(`/goal/api/goals/${goalId}/reflections`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ content: content })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            hideAddReflectionForm();
            viewGoalDetail(goalId);
        }
    });
}

// 编辑反思笔记
function editReflection(reflectionId, currentContent) {
    const newContent = prompt('修改反思笔记:', currentContent);
    if (!newContent || newContent === currentContent) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/reflections/${reflectionId}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ content: newContent })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('修改成功', 'success');
            viewGoalDetail(goalId);
        }
    });
}

// 删除反思笔记
function deleteReflection(reflectionId) {
    if (!confirm('确定要删除这条反思笔记吗？')) return;
    
    const goalId = document.getElementById('detail-goal-id').value;
    
    fetch(`/goal/api/goals/${goalId}/reflections/${reflectionId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            viewGoalDetail(goalId);
        }
    });
}

// 删除目标
function deleteGoal(goalId) {
    if (!confirm('确定要删除这个目标吗？所有相关数据也会被删除。')) return;
    
    fetch(`/goal/api/goals/${goalId}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            loadGoals();
            loadStats();
        }
    });
}

// 一键清除已完成的目标
function clearCompletedGoals() {
    if (!confirm('确定要清除所有已完成的目标吗？所有相关数据也会被删除，此操作不可恢复。')) return;
    
    fetch('/goal/api/goals/clear-completed', {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert(`成功清除 ${result.count} 个已完成的目标`, 'success');
            loadGoals();
            loadStats();
        }
    });
}

// 页面加载
document.addEventListener('DOMContentLoaded', function() {
    loadGoals();
    loadStats();
});
</script>
{% endblock %}

